<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Base\Order;
use App\Models\Base\OrderChargeLevel;
use App\Models\Base\ServerList;
use App\Models\GameLog\LogPayRecord;
use App\Models\Game\PlayerGamedata;
use App\Service\PlayerService;
use App\Service\RequestService;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;

/**
 * 补单.
 */
class OrderRepleteController extends Controller
{
    use ModelForm;
    protected $server_id;

    public function __construct()
    {
        if (Input::get('server_id')) {
            $this->server_id = Input::get('server_id');
        } else {
            $all = ServerList::all();
            $this->server_id = $all[0]->server_id;
        }
        setDB($this->server_id);
    }

    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header(trans('game.order'));
            $content->description(trans('game.order_single'));
            $content->body($this->grid());
        });
    }

    protected function grid()
    {
        $grid = Admin::grid(LogPayRecord::class, function (Grid $grid) {
            $grid->model()->select(DB::raw('*,playerid as playername,orderId as
                order_sn'))->orderBy('time', 'desc');

            $grid->order_sn(trans('game.order_sn'))->display(function ($order_sn) {
                return "{$order_sn}";
            });

            $grid->playerid(trans('game.role_id'));
            $grid->playername(trans('game.role_name'))->display(function ($id) {
                $player = PlayerGamedata::where('id', $id)->pluck('name');

                return $player[0] ?? '';
            });

            $grid->serverid(trans('game.server_name'))->display(function ($server_id) {
                $server = ServerList::where('server_id', $server_id)
                    ->pluck('name');

                return $server[0] ?? '';
            });

            $grid->count(trans('game.amount'));
            $grid->flag(trans('game.status'))->display(function ($flag) {
                return $flag ? "<span class='label bg-green'>".trans('game.is_pay')."</span>" : "<span class='label bg-red'>".trans('game.is_not_pay')."</span>";
            });

            $grid->time(trans('game.order_time'))->display(function ($time) {
                return date('Y-m-d H:i:s', $time);
            })->sortable();

            $grid->timePay(trans('game.pay_time'))->display(function ($time) {
                return date('Y-m-d H:i:s', $time);
            })->sortable();

            $grid->disableExport();
            $grid->disableRowSelector();
            $self = $this;
            $server_id = $self->server_id;
            $grid->actions(function ($actions) use ($grid, $server_id) {
                //删除编辑操作
                $actions->disableEdit();
                $actions->disableDelete();
                //添加查看操作
                $actions->prepend('<a class="" href="'.$actions->getResource().'/'.
                    $actions->row->order_sn.'/replete?serverid='.$server_id
                    .'&flag='.$actions->row->flag.'">'.trans('game.top-up').'</a>');
            });

            // 字段过滤器
            $grid->filter(function ($filter) {
                $filter->setNotWhere(['server_id']);
                $filter->disableIdFilter();
                $filter->equal('server_id', trans('game.server_name'))->select(ServerList::all()
                        ->pluck('name', 'server_id'));
                $filter->equal('flag', trans('game.status'))->select([trans('game.is_not_pay'), trans('game.is_pay')]);
                $filter->equal('orderId', trans('game.order_no'));
                $filter->between('time', trans('game.pay_time'))->date();
            });
        });

        return $grid;
    }

    /**
     * Edit interface.
     *
     * @param $id 订单编号
     *
     * @return Content
     */
    public function replete($order_sn)
    {
        $get = Input::all();
        //补单日志
        Log::warning('补单start', ['order_sn' => $order_sn, 'get' => $get]);
        //判断是否充值过
        if (1 == $get['flag']) {
            Log::error('补单:已经充值过', ['order_sn' => $order_sn]);

            return back()->with(admin_toastr(trans('game.not_repeat_order'), 'error'))->withInput();
        }
        $local_order = Order::where('order_sn', ['order_sn' => $order_sn])
            ->first();
        if ($local_order && in_array($local_order->status, [1, 3])) {
            Log::error('补单:已经充值过', ['order_sn' => $order_sn]);

            return back()->with(admin_toastr(trans('game.not_repeat_order'), 'error'))->withInput();
        }

        if (!$record = LogPayRecord::where('orderId', $order_sn)->first()) {
            Log::error('补单:订单号不存在', ['order_sn' => $order_sn]);

            return back()->with(admin_toastr(trans('game.not_order_no'), 'error'))->withInput();
        }
        //通知游戏服
        $send = RequestService::sendOrderPay($this->server_id, $order_sn,
            $record->platformId, $record->playerid, $record->accountId);
        if ($send) {
            if (isset($local_order->status) && $local_order->status) {
                $local_order->status = 3;
                $local_order->save();
            } else {
                //写入本地表
                if (!$order = $this->insertOrder($record, $order_sn)) {
                    return back()->with(admin_toastr(trans('game.write_local_failure'), 'error'))->withInput();
                }
            }

            return back()->with(admin_toastr(trans('admin.succeeded')));
        }

        return back()->with(admin_toastr(trans('admin.failed'), 'error'))->withInput();
    }

    /**
     * [insertOrder 写入本地数据].
     *
     * @Author   王文凡
     * @DateTime 2018-04-04
     *
     * @version  1.0
     *
     * @return
     */
    protected function insertOrder($record, $order_sn)
    {
        $player = PlayerGamedata::where('id', "$record->playerid")
            ->pluck('name');

        $player_name = $player[0] ?? '无';
        $model = new Order();
        $model->order_sn = $order_sn;
        $model->server_id = $this->server_id;
        $model->userid = $record->userid;
        $model->player_id = $record->playerid;
        $model->platform_id = $record->platformId;
        $model->player_name = $player_name;
        $model->amount = $record->count;
        $model->channel_id = $record->platformId;
        $model->payWay = $record->payWay;
        $model->platform_order_sn = '10000';
        $model->status = 3;
        $model->order_time = time();
        $model->desc = '补单';
        if ($model->save()) {
            return $model;
        } else {
            return false;
        }
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header(trans('game.simulation_prepaid'));
            $content->description(trans('admin.new'));

            $content->body($this->form());
        });
    }

    protected function form()
    {
        return Admin::form(Order::class, function (Form $form) {
            $server = ServerList::all()->pluck('name', 'server_id');
            $form->select('server_id', trans('game.server_name'))->options($server)->rules('required|numeric');
            $form->select('player_id', trans('game.role_name'))
                ->ajaxLoad('server_id', route('api.player'))->rules('required|numeric')->help(trans('game.input_keywords'));
            $form->select('charge_level', trans('game.top-up_gear'))
                ->options(OrderChargeLevel::all()->pluck('name', 'id'))->rules('required|numeric');

            $form->saving(function ($form) {
                $post = request()->all();
                $level = OrderChargeLevel::find($post['charge_level']);
                $order_sn = create_unique();
                $send = RequestService::sendOrderPay($this->server_id, $order_sn,
                    99, $post['player_id'], $post['charge_level'], 1);
                if ($send) {
                    $player = PlayerService::getPayerInfo($post['server_id'], $post['player_id']);
                    $form->model()->status = 3;
                    $form->model()->amount = $level->price;
                    $form->model()->order_sn = $order_sn;
                    $form->model()->userid = $player->userId;
                    $form->model()->player_name = $player->name;
                    $form->model()->platform_id = $player->platformID;
                    $form->model()->channel_id = $player->channelId;
                    $form->model()->pay_time = $form->model()->order_time = time();
                    $form->model()->platform_order_sn = 99;
                    $form->model()->desc = '模拟充值';
                } else {
                    return back()->withInput(admin_toastr(trans('game.gs_communication_failed'), 'error'));
                }
            });
        });
    }
}
